<?
ini_set("display_errors",1);
include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');
include($_SERVER['DOCUMENT_ROOT'].'/filter.libs.php');

$bits = explode('.',$_SERVER['SERVER_NAME']);
$domain = $bits[0];

$row = getRow("SELECT portal_id,title,user_id,realname,public,readable FROM portal INNER JOIN user USING (user_id) WHERE domain = ".dbQuote($domain)." AND status_id = 1");

if (empty($row['portal_id'])) {
	header("HTTP/1.0 404 Not Found");
	print "<html><head>";
	print "<title>Not found!</title>";
	print "</head><body>";
	print "<p>The page you are looking for is not available</p>";
	
	print "<p><a href=\"http://www.geographs.org/portals/?ref=$domain\">Try the Portal Homepage</a></p>";
	print "</body></html>";
	print str_repeat(" ",500);
	exit;
}

$this_portal = $id = intval($row['portal_id']);
$title = $row['title'];

$row['count'] = count_active($id);

$page_title = "Related Portals";
include($_SERVER['DOCUMENT_ROOT'].'/header.inc.php');

if ($row['public'] != 'Y') {
	print "<p>NOTE: Only Public Portals work with this feature. This might change in the future.</p>";
	
	include($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php');

	exit;
}

#########################

print "<H2>Related Portals</h2>";
print "<p>(sharing common images)</p>";

 
	include($_SERVER['DOCUMENT_ROOT'].'/geograph/sphinxwrapper.class.php'); 
	
	$CONF['sphinx_host'] = "localhost";
	$CONF['sphinx_port']= 3312;
	$CONF['sphinx_index']= "portalimages";

	
	
	$sphinx = new sphinxwrapper('');



 
	$sphinx->pageSize = $pgsize = 10;

	
	$pg = (!empty($_GET['page']))?intval(str_replace('/','',$_GET['page'])):0;
	if (empty($pg) || $pg < 1) {$pg = 1;}
	
	$cacheid .=".".$pg;
	
		
		$offset = (($pg -1)* $sphinx->pageSize)+1;
		
		if ($offset < (1000-$pgsize) ) { 
			#$sphinx->processQuery();
		
			$cl = $sphinx->_getClient();
			
			//find images both in this portal and other portals. 
			
			$cl->setFilter('portal_id',array($id));
			
			$portals = getAssoc("SELECT portal_id,domain,title,realname,user_id FROM `portal` LEFT JOIN user USING (user_id) WHERE status_id = 1 AND public = 'Y' AND portal_id != $id");
			$cl->setFilter('portal_id',array_keys($portals));
			
			$cl->SetGroupBy('portal_id',SPH_GROUPBY_ATTR,"portal_id DESC");
			
			$cl->SetArrayResult(true);
			
			$ids = $sphinx->returnIds($pg,'portalimages');
			
			
			
			if ($_GET['d']) {
				print_rp($cl);
				print_rp($sphinx->res);
			}
			
			if (!empty($ids) && count($ids) > 1) {
				
				$sql = array();
				$sql['columns'] = 'gridimage_id,title,realname,user_id,grid_reference,comment,imagetaken,imageclass';
				$sql['tables'] = array();
				
				$sql['tables'][] = "p2.gridimage{$id}_bi_view AS gi";
				
				$sql['wheres'] = array();
				if ($cl->_arrayresult) {
					//cos used SetArrayResult ids are just squencial
					
					$gids = array();
					foreach ($ids as $idx => $id) {
						$gids[] = $sphinx->res['matches'][$id]['id'];
					}
					$sql['wheres'][] = "gridimage_id IN(".join(",",$gids).")";
				} else {
					$sql['wheres'][] = "gridimage_id IN(".join(",",$ids).")";
				}
			
				
				$sql['order']= 'NULL'; //we going to reorder anyway
				$sql['limit'] = $sphinx->pageSize;

			
				
				$query = sqlMakeQuery($sql);
				$rows = getAssoc($query);
				
				
				$sphinx->resultCount--; //remove the current portal :)
				
				$final = min($offset+$sphinx->pageSize-1,$sphinx->resultCount);
				print "<div style=\"float:right\">{$offset}..{$final} of {$sphinx->resultCount}</div>";
				
				foreach ($ids as $idx => $id) {
					if ($cl->_arrayresult) {
						//cos used SetArrayResult ids are just squencial
						$gid = $sphinx->res['matches'][$id]['id'];
						$c = $rows[$gid];
						$c['gridimage_id'] = $gid;
					} else {
						$c = $rows[$id];
						$c['gridimage_id'] = $id;
					}
					
					$portal_id = $sphinx->res['matches'][$id]['attrs']['@groupby'];
					
					if ($this_portal == $portal_id ) {
						//nothing!
					} elseif ($c) {
					
					?>
					<div style="clear:left; border-top:1px solid #eeeeee">
					  <div style="float:left;position:relative; width:130px; margin-right:10px">
					  <div align="center">
					  <a title="<? ehec('grid_reference'); ?> : <? ehec('title'); ?> by <? ehec('realname'); ?> - click to view full size image" href="http://www.geograph.org.uk/photo/<? echo $c['gridimage_id']; ?>"><img src="<? echo gGUc($c); ?>" width="70%"  /></a></div>
					  </div>

					  <? echo $offset; ?>. <big><b><a href="http://<? echo he($portals[$portal_id]['domain']); ?>.portal.geographs.org/"><? echo he($portals[$portal_id]['title']); ?></a></b></big> by
					  <a href="http://www.geographs.org/portals/profile/<? echo he($portals[$portal_id]['user_id']); ?>"><? echo he($portals[$portal_id]['realname']); ?></a>
					  
					  <br/><br/>
					  
					  
					  
					  <small>(image: <a href="http://www.geograph.org.uk/gridref/<? ehec('grid_reference'); ?>"><tt><? ehec('grid_reference'); ?></tt></a>
					  <a href="http://www.geograph.org.uk/photo/<? echo $c['gridimage_id']; ?>"><? ehec('title'); ?></a>
					   by <a href="<? echo linktoself(array('bi_id'=>$c['user_id'],'delete'=>'page')); ?>"><? ehec('realname'); ?></a></small>)<br/>

					 
					  <br style="clear:left"/>
					</div>
					<?
						$offset++;
					} else {
						?>
						<div style="clear:left; border-top:1px solid #eeeeee">
							 <? echo $offset; ?>. Image <a href="http://www.geograph.org.uk/photo/<? echo $id; ?>">http://www.geograph.org.uk/photo/<? echo $id; ?></a> not available in this portal at the moment.
						</div>
						<?
						$offset++;
					}
					
					
				}
								
				if ($sphinx->resultCount > $sphinx->pageSize) {
					print " &middot; &nbsp; ";
					if ($pg > 1) {
						$last = $pg-1;
						print "<a href=\"search.php?q=".urlencode($sphinx->qclean)."&amp;page=$last\">&lt; &lt; <b>Prev page</b> </a> &nbsp; &middot; ";
					}
					if ($pg < $sphinx->numberOfPages) {
						$next = $pg+1;
						print " &nbsp; <a href=\"search.php?q=".urlencode($sphinx->qclean)."&amp;page=$next\"><b>Next page</b> &gt;&gt;</a> &nbsp; &middot;";
					}
				}
		
				print "<br style='clear:both'><p class=\"message\">{$sphinx->query_info}</p>";
				
				
				
				
				
				
			} else {
				print "<p>No results for your query.</p>";
							
			}
			
			
			
		} else {
			print "Search will only return 1000 results - please refine your search";
		
		}



include($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php');
